package com.shao.compress.impl;

import com.shao.compress.Compressor;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/4/30 15:08
 */
@Slf4j
public class GzipCompress implements Compressor {
    @Override
    public byte[] compress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return new byte[0];
        }
        try(
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)
        ) {
            gzipOutputStream.write(bytes);
            gzipOutputStream.finish(); // 显式完成写入
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("使用Gzip压缩时发生异常", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public byte[] unCompress(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return new byte[0];
        }
        try (
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            GZIPInputStream gzipInputStream = new GZIPInputStream(bais);
        ){
            return gzipInputStream.readAllBytes();
        } catch (IOException e) {
            log.error("使用Gzip解压缩时发生异常", e);
            throw new RuntimeException(e);
        }
    }
}
